package database;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Vector;

import object.Position;
import utility.StringUtil;
import clientMain.Login;
import clientMain.Main;

public class PositionDelegate {
	
	public Vector<Position> getlistPosition(int page, String sort, boolean flag) {
		Vector<Position> list = new Vector<Position>();
		try {
			Login.conn.setAutoCommit(false);
			CallableStatement cst = Login.conn.prepareCall("{ call sp_ListPosition(?,?,?,?) }");
			cst.setInt(1, Main.record);
			cst.setInt(2, page);
			cst.setString(3, sort);
			cst.setBoolean(4, flag);
			ResultSet rs = cst.executeQuery();
			while(rs.next()){
				Position position = new Position();
				position.setPosId(rs.getInt("Pos_Id"));
				position.setPosName(StringUtil.getFilterIllegal(rs.getString("Pos_Name")));
				if(page !=0){
					position.setPosDes(StringUtil.getFilterIllegal(rs.getString("Pos_Describe")));
				}
				list.add(position);
			}
			Login.conn.commit();
		} catch (Exception e) {
			e.printStackTrace();
			list = null;
		}
		
		return list;
	}
	public boolean insertPos(Position pos, int userInsert){
		boolean flag = false;
		try {
			Login.conn.setAutoCommit(false);
			CallableStatement cst = Login.conn.prepareCall("{call sp_InsertPos(?,?,?)}");
			cst.setString(1, StringUtil.setFilterIllegal(pos.getPosName()));
			cst.setString(2, StringUtil.setFilterIllegal(pos.getPosDes()));
			cst.setInt(3, userInsert);
			cst.executeUpdate();
			Login.conn.commit();
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
		return flag;
	}
	public boolean updatePos(Position pos, int userUpdate){
		boolean flag = false;
		try {
			Login.conn.setAutoCommit(false);
			CallableStatement cst = Login.conn.prepareCall("{call sp_UpdatePos(?,?,?,?)}");
			cst.setInt(1, pos.getPosId());
			cst.setString(2, StringUtil.setFilterIllegal(pos.getPosName()));
			cst.setString(3, StringUtil.setFilterIllegal(pos.getPosDes()));
			cst.setInt(4, userUpdate);
			cst.executeUpdate();
			Login.conn.commit();
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
			
		}
		return flag;
	}
	public boolean CheckInsertPosName(String name){
		boolean rs = false;
		try {	
			  Statement st = Login.conn.createStatement();
			  ResultSet  traVe = st.executeQuery("select  * from Position where Pos_Name  =N'"+name+"'");
			  while (traVe.next()) { 
				  rs = true;
			  }
			  return rs;
			  
		} catch (Exception e) {
			
		}
		return rs;
	}
}
